/**   
* @Title: StocklistService.java 
* @Package com.csis.system.service 
* @Description: TODO
* @author dailey  
* @date 2012-10-8
* @version V1.0   
*/
package com.csis.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csis.framework.db.BaseDao;
import com.csis.framework.domain.Condition;
import com.csis.system.common.IStaticData;
import com.csis.system.common.WebUtil;
import com.csis.system.domain.Stocklist;
import com.csis.system.domain.StocklistFormBean;

/**
 * @author dailey
 *
 */
@Service
public class StocklistService {

	@Autowired
	private BaseDao baseDao;

	public Stocklist load(String stockno) {
		Stocklist stocklist = baseDao.load(Stocklist.class, stockno);
		return stocklist;
	}

	public StocklistFormBean list(StocklistFormBean formBean) {
		Integer currUserId = formBean.getUserId();
		if (currUserId == null) {
			return formBean;
		}
		String sql = getSearchSql(formBean);

		Condition condition = formBean.getCondition();
		if (condition != null) {
			sql = condition.getCondition(sql);
		}
		// importance
		int maxCount = getMaxCount(formBean);
		formBean.getPage().setMaxCount(maxCount);
		sql = formBean.getPage().perPageSql(sql);
		List<Stocklist> beans = baseDao.query4SingleTable(Stocklist.class, sql);
		formBean.setBeans(beans);
		return formBean;
	}

	public String getSearchSql(StocklistFormBean formBean) {
		Integer currUserId = formBean.getUserId();
		String sql = "SELECT * FROM " + IStaticData.TABLE_STOCKLIST + " WHERE 1=1 ";
		if (currUserId != null && !WebUtil.isShowAll(formBean)) {
			sql += " AND " + IStaticData.COLUMN_STOCKLIST_USERID + " = " + currUserId + " ";
		}
		return sql;
	}

	/**
	 * @return
	 */
	public int getMaxCount(StocklistFormBean formBean) {
		return baseDao.getMaxCount(getSearchSql(formBean));
	}

	@Transactional
	public void save(Stocklist stocklist) {
		if (stocklist.getId() == null) {
			stocklist.setId(WebUtil.generateNo());
			baseDao.persist(stocklist);
		} else {
			baseDao.merge(stocklist);
		}
	}

}
